const express = require('express');
const router = express.Router();
const db = require('../utils/db');
const jsonwebtoken = require('jsonwebtoken');
const utility = require('utility');
router.post('/reguser', async(req, res) => {
    req.body.password = utility.md5(req.body.password)
    let r = await db('insert into user set ?', req.body);
    if (r && r.affectedRows > 0) {
        res.send({
            status: 0,
            message: '注册成功',
        });
    } else {
        res.send({
            status: 1,
            message: '注册失败',
        })
    }
});
router.post('/login', async(req, res) => {
    let password = utility.md5(req.body.password);
    let username = req.body.username;
    let r = await db('select * from user where username = ? and password = ?', [username, password])
    if (r && r.length > 0) {
        res.send({
            status: 0,
            message: '登录成功',
            token: 'bearer ' + jsonwebtoken.sign({ username: req.body.username, id: r[0].id }, 'bigevent', { expiresIn: '2 days' })
        })
    } else {
        res.send({
            status: 1,
            message: '登录失败'
        })
    }
})

module.exports = router;